package com.salesmanager.core.business.user.dao;

import com.mysema.query.jpa.JPQLQuery;
import com.mysema.query.jpa.impl.JPAQuery;
import com.salesmanager.core.business.generic.dao.SalesManagerEntityDaoImpl;
import com.salesmanager.core.business.user.model.QGroup;
import com.salesmanager.core.business.user.model.QUser;
import com.salesmanager.core.business.user.model.User;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository("userDao")
public class UserDaoImpl extends SalesManagerEntityDaoImpl<Long, User> implements
		UserDao {
	
	@Override
	public User getByUserName(String userName) {
		
		
		QUser qUser = QUser.user;
		QGroup qGroup = QGroup.group;
		
		JPQLQuery query = new JPAQuery (getEntityManager());
		
		query.from(qUser)
			.innerJoin(qUser.groups, qGroup).fetch()
			.where(qUser.adminName.eq(userName));

		User user = query.uniqueResult(qUser);
		return user;
	}

    @Override
    public User getByUserNameAndType(String userName, int type) {
        QUser qUser = QUser.user;
        QGroup qGroup = QGroup.group;

        JPQLQuery query = new JPAQuery (getEntityManager());

        query.from(qUser)
                .innerJoin(qUser.groups, qGroup).fetch()
                .where(qUser.adminName.eq(userName).and(qUser.userType.eq(type)));

        User user = query.uniqueResult(qUser);
        return user;
    }

    @Override
	public User getByTelPhone(String telPhone) {


		QUser qUser = QUser.user;
		QGroup qGroup = QGroup.group;

		JPQLQuery query = new JPAQuery (getEntityManager());

		query.from(qUser)
				.innerJoin(qUser.groups, qGroup).fetch()
				.where(qUser.telPhone.eq(telPhone));

		User user = query.uniqueResult(qUser);
		return user;
	}

	@Override
	public User getById(Long id) {
		
		
		QUser qUser = QUser.user;
		QGroup qGroup = QGroup.group;
		
		JPQLQuery query = new JPAQuery (getEntityManager());
		
		query.from(qUser)
			.innerJoin(qUser.groups, qGroup).fetch()
			.where(qUser.id.eq(id));

		User user = query.uniqueResult(qUser);
		return user;
	}

	@Override
	public List<User> listUser() {
		QUser qUser = QUser.user;
		JPQLQuery query = new JPAQuery (getEntityManager());
		
		query.from(qUser)
			.innerJoin(qUser.groups).fetch()
			.orderBy(qUser.id.asc());
		
		return query.distinct().list(qUser);
				//listDistinct(qUser);
	}


}
